import socket,threading

# 线程
def client_thread(mysocket,addr):
    mtu = 1024
    try:
        while True:
            data = mysocket.recv(mtu).decode("utf-8")
            if data:
                print("用户{} 发送了: {}".format(addr, data))
                mysocket.send("已连接".encode("utf-8"))
            else:
                break

    except socket.errno as e:
        print("Socket error: %s" % str(e))
    except Exception as e:
        print("Other exception: %s" % str(e))
    finally:
        print("%s(%s) 断开连接" % (addr))
        mysocket.close()

class TcpServer:
    def __init__(self):
        
        # 创建socket对象
        self.s = socket.socket()
        # 绑定ip和端口，表明是服务端
        self.s.bind(("127.0.0.1", 8888))
        self.s.listen(10)#设置最大监听量
    
    def start(self):
        print("start listen:{}".format(self.s))
        while True:
            # 接受客户端连接
            conn, addr = self.s.accept()
            print('{}连接已经建立'.format(addr))
            t = threading.Thread(target=client_thread, args=(conn,addr))
            t.start()



server = TcpServer()

server.start()
